package com.eshore.norm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormNetwork;
import com.eshore.norm.mapper.NormNetworkMapper;
import com.eshore.norm.pojo.po.NormNetworkPO;
import com.eshore.norm.service.INormNetworkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eshore.norm.util.DateUtils;
import com.eshore.norm.util.ListStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 网络列表 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Service
public class NormNetworkServiceImpl extends ServiceImpl<NormNetworkMapper, NormNetwork> implements INormNetworkService {

    @Override
    public void dataImport(NormNetworkPO po) {
        Optional<NormNetworkPO> po_optional = Optional.ofNullable(po);
        po_optional.ifPresent(s -> {
            Optional<List<NormNetworkPO.NetworksDTO>> dto_optional = Optional.ofNullable(s.getNetworks());
            dto_optional.ifPresent(item -> {
                List<String> newNetworkIds = item.stream().map(NormNetworkPO.NetworksDTO::getId).collect(Collectors.toList());
                cleanOldData(Const.CONFIG_ID, newNetworkIds);
                //将po转化成实体对象入库
                List<NormNetwork> entityList = toNormNetwork(Const.CONFIG_ID, dto_optional);
                if (!CollectionUtils.isEmpty(entityList)) {
                    getBaseMapper().insertOrUpdateBatch(entityList);
                }
            });
        });
    }

    /**
     * 删除现已不存在的数据，保持同步一致
     *
     * @param configId
     * @param newNetworkIds 需要同步的索引Id集合
     * @author v-chenjl62
     * @date 2024/1/10
     */
    private void cleanOldData(Long configId, List<String> newNetworkIds) {
        List<String> oldNetworkIds = lambdaQuery().eq(NormNetwork::getConfigId, configId).list().stream().map(NormNetwork::getNetworkId).collect(Collectors.toList());
        //筛选出差异的imagesId即为多余的需要删除
        oldNetworkIds.removeAll(newNetworkIds);
        if (!CollectionUtils.isEmpty(oldNetworkIds)) {
            getBaseMapper().delete(new QueryWrapper<NormNetwork>().in("network_id", oldNetworkIds));
        }
    }

    private List<NormNetwork> toNormNetwork(Long configId, Optional<List<NormNetworkPO.NetworksDTO>> list_optional) {
        return list_optional.get().stream().map(item -> {
            NormNetwork entity = new NormNetwork();
            BeanUtils.copyProperties( item, entity,"id","netScope","extraDhcpOpts","segments","availabilityZoneHints","availabilityZones","subnets","tags");
            entity.setNetworkId(item.getId());//唯一索引
            entity.setNetScope(JSON.toJSONString(item.getNetScope(), SerializerFeature.WriteMapNullValue));
            entity.setExtraDhcpOpts(JSON.toJSONString(item.getExtraDhcpOpts(), SerializerFeature.WriteMapNullValue));
            entity.setSegments(JSON.toJSONString(item.getSegments(), SerializerFeature.WriteMapNullValue));
            entity.setAvailabilityZoneHints(JSON.toJSONString(item.getAvailabilityZoneHints(), SerializerFeature.WriteMapNullValue));
            entity.setAvailabilityZones(JSON.toJSONString(item.getAvailabilityZones(), SerializerFeature.WriteMapNullValue));
            entity.setSubnets(ListStringUtils.listToString(item.getSubnets()));
            entity.setTags(ListStringUtils.listToString(item.getTags()));

            entity.setId(IdWorker.getId());
            entity.setConfigId(configId);
//            entity.setCreateDate(LocalDateTime.now());
//            entity.setUpdateDate(LocalDateTime.now());
            entity.setCreateDate(DateUtils.parse(item.getCreatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            entity.setUpdateDate(DateUtils.parse(item.getUpdatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            return entity;
        }).collect(Collectors.toList());
    }
}
